package com.ai;

import javax.sound.sampled.*;
import java.io.File;
import java.io.IOException;
import java.io.SequenceInputStream;

/**
 * 音频的拆解工具
 */
public class AudioProcessor {

    // 拆分音频文件
    public void splitAudio(File audioFile, int startTime, int endTime, File outputFile) throws IOException, UnsupportedAudioFileException {
        AudioInputStream audioInputStream = AudioSystem.getAudioInputStream(audioFile);
        AudioFormat format = audioInputStream.getFormat();
        
        // 计算开始和结束的字节位置
        long startByte = (long) (startTime * format.getFrameRate() * format.getFrameSize());
        long endByte = (long) (endTime * format.getFrameRate() * format.getFrameSize());
        
        // 跳转到开始位置
        audioInputStream.skip(startByte);
        
        // 读取音频数据
        AudioInputStream outputStream = new AudioInputStream(audioInputStream, format, (endByte - startByte) / format.getFrameSize());
        
        // 写入输出文件
        AudioSystem.write(outputStream, AudioFileFormat.Type.WAVE, outputFile);
        
        audioInputStream.close();
        outputStream.close();
    }

    // 拼接音频文件
    public void concatenateAudio(File[] audioFiles, File outputFile) throws IOException, UnsupportedAudioFileException {
        AudioInputStream appendedFiles = null;

        for (File audioFile : audioFiles) {
            AudioInputStream audioInputStream = AudioSystem.getAudioInputStream(audioFile);
            if (appendedFiles == null) {
                appendedFiles = audioInputStream;
            } else {
                appendedFiles = new AudioInputStream(
                        new SequenceInputStream(appendedFiles, audioInputStream),
                        appendedFiles.getFormat(),
                        appendedFiles.getFrameLength() + audioInputStream.getFrameLength()
                );
            }
        }

        // 写入输出文件
        AudioSystem.write(appendedFiles, AudioFileFormat.Type.WAVE, outputFile);
        
        if (appendedFiles != null) {
            appendedFiles.close();
        }
    }

    public static void main(String[] args) {
        AudioProcessor processor = new AudioProcessor();
        
        // 示例：拆分音频
        try {
            processor.splitAudio(new File("input.wav"), 10, 20, new File("output_split.wav")); // 拆分10秒到20秒
            System.out.println("音频拆分完成");
        } catch (Exception e) {
            e.printStackTrace();
        }

        // 示例：拼接音频
        try {
            File[] audioFiles = { new File("part1.wav"), new File("part2.wav") };
            processor.concatenateAudio(audioFiles, new File("output_concatenated.wav"));
            System.out.println("音频拼接完成");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
} 